﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using AppRes = WindowsPhoneCommands.Resources;
using EnvDTE;
using EnvDTE80;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Interaction logic for PhoneProjectLocation.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class PhoneProjectLocation : UserControl
    // ReSharper restore RedundantExtendsListEntry
    {
        private bool _loaded;
        private readonly ToolWindowPane _parentWindow;
        private string _projectName;
        private string _rootproject;

        public WindowsPhoneCommandsPackage Package
        {
            get
            {
                return (WindowsPhoneCommandsPackage)_parentWindow.Package;
            }
        }

        public PhoneProjectLocation()
            : this(null)
        {

        }

        public PhoneProjectLocation(ToolWindowPane parentWindow)
        {
            _parentWindow = parentWindow;

            InitializeComponent();

            Loaded += PhoneProjectControlLoaded;

        }

        private void LoadDataResources(Cursor oldcur)
        {
            CreateListLng();

            var seletedProject = EnvPhoneDevice.FindProjectByName(Package.EnvDte, _projectName);

            if (EnvPhoneDevice.GetIsAppPhone(seletedProject))
            {
                CboAccessMod.SelectedIndex = -1;
                foreach (var item in CboAccessMod.Items.Cast<ComboBoxItem>().Where(item => item.Tag.ToString() == "N"))
                {
                    CboAccessMod.SelectedItem = item;
                    break;
                }
            }

            var directoryInfo = new FileInfo(seletedProject.FullName).Directory;
            if (directoryInfo != null)
            {
                _rootproject = directoryInfo.FullName + "\\";
            }

            CboPrjLng.ItemsSource = EnvPhoneDevice.PhoneLanguageSupport().Values;
            CboPrjLng.SelectedIndex = -1;

            var folders = EnvPhoneDevice.GetListFolderFromProject(seletedProject).ToList();
            folders.Insert(0, AppRes.RootProject);
            CboTargetFolder.ItemsSource = folders;
            CboTargetFolder.SelectedItem = null;

            var res = EnvPhoneDevice.GetListNeutralResourcesFromProject(seletedProject);
            CboFilesResx.ItemsSource = res;

            if (File.Exists(_rootproject + UserSettings.Current.FolderLanguages + "\\" + UserSettings.Current.NeutralResource))
            {
                ExistFile.Visibility = Visibility.Visible;
                ChkNewResource.IsChecked = false;
                ChkNewResource.IsEnabled = false;
            }
            else
            {
                ChkNewResource.IsChecked = true;
                ChkNewResource.IsEnabled = true;
                ExistFile.Visibility = Visibility.Hidden;
                CboFilesResx.IsEnabled = false;
                CboTargetFolder.IsEnabled = false;
            }


            var defres = res.FirstOrDefault(d => d.ToLower().Contains(UserSettings.Current.NeutralResource.ToLower()));
            if (defres != null)
            {
                ChkNewResource.IsChecked = false;
                CboFilesResx.IsEnabled = true;
                CboFilesResx.Text = defres;
                CboTargetFolder.IsEnabled = true;
            }

            var toolwin = (WpcLocationToolWindow)_parentWindow;

            var supcult = toolwin.SupportedCultures.Aggregate(string.Empty, (current, s) => current + (s + ";"));
            if (supcult.EndsWith(";"))
            {
                supcult = supcult.Substring(0, supcult.Length - 1);
            }
            CurrSuppCult.Text = AppRes.XSupportedCultures + " " + supcult;

            SetNeutralLng(toolwin.NeutralResource, true);
            MarkPatternResources((string)CboFilesResx.SelectedItem,(string)CboTargetFolder.SelectedItem);

            ValidateFields();

            Cursor = oldcur;
            IsEnabled = true;
        }

        private void PhoneProjectControlLoaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                var toolwin = (WpcLocationToolWindow)_parentWindow;
                _projectName = toolwin.OwnerProject;
                _parentWindow.Caption = AppRes.TitePhoneLocation + " (" + _projectName + ")";

                Background = VsTheming.GetDialogBackground();
                Foreground = VsTheming.GetWindowText();
                ExistFile.Foreground = VsTheming.GetColorError();
                DefaultNewresource.Text = "(" + UserSettings.Current.FolderLanguages + "\\" + UserSettings.Current.NeutralResource + ")";
                DefaultHelper.Text = "(" + UserSettings.Current.XamlClassHelper + ")";
                var oldcur = Cursor;
                Cursor = Cursors.Wait;
                IsEnabled = false;
                Dispatcher.BeginInvoke(new Action<Cursor>(LoadDataResources), DispatcherPriority.Normal, new object[] { oldcur });
            }
            _loaded = true;
        }

        private void SetNeutralLng(string defaultvalue, bool first)
        {
            if (first)
            {
                CboPrjLng.Text = EnvPhoneDevice.GetValuePhoneLanguageSupport(defaultvalue);
                defaultvalue = CboPrjLng.Text;
            }
            var knlg = EnvPhoneDevice.GetKeyPhoneLanguageSupport(defaultvalue);

            //clear disabled neutral language
            foreach (var chk in from object obj in Col0SupLng.Children select obj as CheckBox into chk where chk != null && !chk.IsEnabled select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = true;
                chk.Opacity = 1;
                chk.Content = chk.Content.ToString().Replace("***", "");
            }
            foreach (var chk in from object obj in Col1SupLng.Children select obj as CheckBox into chk where chk != null && !chk.IsEnabled select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = true;
                chk.Opacity = 1;
                chk.Content = chk.Content.ToString().Replace("***", "");
            }
            foreach (var chk in from object obj in Col2SupLng.Children select obj as CheckBox into chk where chk != null && !chk.IsEnabled select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = true;
                chk.Opacity = 1;
                chk.Content = chk.Content.ToString().Replace("***", "");
            }
            if (knlg == null)
            {
                return;
            }

            //disabled neutral language
            foreach (var chk in from object obj in Col0SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == knlg select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = false;
                chk.Opacity = 0;
            }
            foreach (var chk in from object obj in Col1SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == knlg select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = false;
                chk.Opacity = 0;
            }
            foreach (var chk in from object obj in Col2SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == knlg select chk)
            {
                chk.IsChecked = false;
                chk.IsEnabled = false;
                chk.Opacity = 0;
            }
        }

        private void CreateListLng()
        {
            var values = EnvPhoneDevice.PhoneLanguageSupport().Values.ToArray();
            var keys = EnvPhoneDevice.PhoneLanguageSupport().Keys.ToArray();
            var part = values.Length / 3;
            Col0SupLng.Children.Clear();
            Col1SupLng.Children.Clear();
            Col2SupLng.Children.Clear();
            for (var i = 0; i < part; i++)
            {
                var check = new CheckBox { Tag = keys[i], Content = values[i], Margin = new Thickness(0, 5, 0, 3) };
                Col0SupLng.Children.Add(check);
            }
            for (var i = part; i < part * 2; i++)
            {
                var check = new CheckBox { Tag = keys[i], Content = values[i], Margin = new Thickness(0, 5, 0, 3) };
                Col1SupLng.Children.Add(check);
            }
            for (var i = (part * 2); i < values.Length; i++)
            {
                var check = new CheckBox { Tag = keys[i], Content = values[i], Margin = new Thickness(0, 5, 0, 3) };
                Col2SupLng.Children.Add(check);
            }
        }

        private void CboPrjLngSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetNeutralLng(e.AddedItems.Count > 0 ? (String)e.AddedItems[0] : null, false);
            Dispatcher.BeginInvoke(new Action<string,string>(MarkPatternResources), DispatcherPriority.Normal, new[] { CboFilesResx.SelectedItem,CboTargetFolder.SelectedItem});
        }

        private void ChkNewResourceClick(object sender, RoutedEventArgs e)
        {
            // ReSharper disable PossibleInvalidOperationException
            if (ChkNewResource.IsChecked.Value)
            // ReSharper restore PossibleInvalidOperationException
            {
                CboFilesResx.SelectedIndex = -1;
                CboFilesResx.IsEnabled = false;
                CboTargetFolder.SelectedIndex = -1;
                CboTargetFolder.IsEnabled = false;
            }
            else
            {
                CboFilesResx.IsEnabled = true;
                CboTargetFolder.IsEnabled = true;
            }
            MarkPatternResources((string)CboFilesResx.SelectedItem,(string)CboTargetFolder.SelectedItem);
            ValidateFields();
        }

        private void MarkPatternResources(string neutrallocalpath,string targetfolder)
        {
            if (string.IsNullOrEmpty(neutrallocalpath) || string.IsNullOrEmpty(targetfolder))
            {
                SetNeutralLng(CboPrjLng.Text, false);
                return;
            }

            var defres = _rootproject + neutrallocalpath;
            var fi = new FileInfo(defres);
            var ext = fi.Extension;
            var fname = fi.Name.Replace(ext, "");

            if (targetfolder == AppRes.RootProject)
            {
                targetfolder = string.Empty;
            }
            var resfolder = _rootproject + targetfolder;
            if (!resfolder.EndsWith("\\"))
            {
                resfolder += "\\";
            }

            var keys = EnvPhoneDevice.PhoneLanguageSupport().Keys.ToArray();
            var existkey = (from key in keys let resfname = fname + "." + key + ext where File.Exists(resfolder + resfname) select key).ToList();
            existkey.AddRange((from key in keys let resfname = fname + "." + key.Substring(0, 2) + ext where File.Exists(resfolder + resfname) select key).ToArray());
            SetNeutralLng(CboPrjLng.Text, false);

            foreach (var suplng in existkey)
            {
                var suplng1 = suplng;
                foreach (var chk in from object obj in Col0SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == suplng1 select chk)
                {
                    var it = Package.EnvDte.Solution.FindProjectItem(fname + "." + suplng1 + ext);
                    if (it == null)
                    {
                        chk.Content = chk.Content + " ***";
                    }
                    chk.IsChecked = false;
                    chk.IsEnabled = false;
                }
                foreach (var chk in from object obj in Col1SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == suplng1 select chk)
                {
                    var it = Package.EnvDte.Solution.FindProjectItem(fname + "." + suplng1 + ext);
                    if (it == null)
                    {
                        chk.Content = chk.Content + " ***";
                    }
                    chk.IsChecked = false;
                    chk.IsEnabled = false;
                }
                foreach (var chk in from object obj in Col2SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.Tag.ToString() == suplng1 select chk)
                {
                    var it = Package.EnvDte.Solution.FindProjectItem(fname + "." + suplng1 + ext);
                    if (it == null)
                    {
                        chk.Content = chk.Content + " ***";
                    }
                    chk.IsChecked = false;
                    chk.IsEnabled = false;
                }
            }
        }

        private void BntSaveClick(object sender, RoutedEventArgs e)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            IsEnabled = false;
            Dispatcher.BeginInvoke(new Action<Cursor>(CreateLocationProject), DispatcherPriority.ApplicationIdle, new object[] { oldcur });
        }

        private static int Adorne(Control control, bool error, string tootip)
        {
            if (error)
            {
                var colorerr = VsTheming.GetColorError();
                if (control.BorderBrush != colorerr)
                {
                    control.Tag = control.BorderBrush;
                    control.BorderBrush = colorerr;
                    control.ToolTip = tootip;
                }
            }
            else
            {
                if (control.BorderBrush != control.Tag && control.Tag != null)
                {
                    control.BorderBrush = (Brush)control.Tag;
                }
            }
            return error ? 1 : 0;
        }

        private void ValidateFields()
        {
            var qtderr = 0;
            qtderr += Adorne(CboPrjLng, CboPrjLng.SelectedItem == null, AppRes.RequiredField);
            // ReSharper disable PossibleInvalidOperationException
            if (!ChkNewResource.IsChecked.Value)
            {
                qtderr += Adorne(CboFilesResx, CboFilesResx.SelectedItem == null, AppRes.RequiredField);
                qtderr += Adorne(CboTargetFolder, CboTargetFolder.SelectedItem == null, AppRes.RequiredField);
            }
            // ReSharper restore PossibleInvalidOperationException
            BntSave.IsEnabled = (qtderr == 0);
        }

        private void CboPrjLngLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields();
        }

        private void CboFilesResxLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields();
        }

        private void CreateLocationProject(Cursor oldcur)
        {
            var seletedProject = EnvPhoneDevice.FindProjectByName(Package.EnvDte, _projectName);
            try
            {

                #region update neutral language project (AssemblyInfo.cs)

                seletedProject.Properties.Item("NeutralResourcesLanguage").Value =
                    EnvPhoneDevice.GetKeyPhoneLanguageSupport(CboPrjLng.Text);
                var assitem = Package.EnvDte.Solution.FindProjectItem("AssemblyInfo.cs");
                if (assitem != null)
                {
                    if (!assitem.IsOpen)
                    {
                        assitem.Open();
                        if (!assitem.Document.Saved)
                        {
                            assitem.Document.Save();
                        }
                        assitem.Document.Close();
                    }
                }

                #endregion

                #region create folder to language location

                ProjectItem folderItem;
                // ReSharper disable PossibleInvalidOperationException
                if (ChkNewResource.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    folderItem = EnvPhoneDevice.CreateFolderProject(seletedProject, UserSettings.Current.FolderLanguages);
                }
                else
                {
                    // ReSharper disable PossibleNullReferenceException
                    var namefolder = string.Empty;
                    if (CboTargetFolder.SelectedIndex > 0)
                    {
                        namefolder = (string)CboTargetFolder.SelectedItem;
                    }
                    var fdi = new  DirectoryInfo(_rootproject + namefolder).FullName.Replace(_rootproject, "");
                    // ReSharper restore PossibleNullReferenceException
                    folderItem = EnvPhoneDevice.FolderExistProject(seletedProject, fdi);
                }

                #endregion

                #region create neutral language

                var soln = (Solution2)Package.EnvDte.Solution;
                var templatePath = soln.GetProjectItemTemplate(Constants.TemplateNameResource, seletedProject.Kind);

                ProjectItem neutralResxItem;
                // ReSharper disable PossibleInvalidOperationException
                if (ChkNewResource.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    folderItem.ProjectItems.AddFromTemplate(templatePath, UserSettings.Current.NeutralResource);
                    neutralResxItem = folderItem.ProjectItems.Item(UserSettings.Current.NeutralResource);
                }
                else
                {
                    neutralResxItem = Package.EnvDte.Solution.FindProjectItem(_rootproject + CboFilesResx.Text);
                }
                if (neutralResxItem.IsOpen)
                {
                    neutralResxItem.Document.ActiveWindow.Visible = false;
                }

                if (!neutralResxItem.Properties.Item("CustomTool").Value.Equals("PublicResXFileCodeGenerator"))
                {
                    neutralResxItem.Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
                }
                if (neutralResxItem.Document != null && !neutralResxItem.Document.Saved)
                {
                    neutralResxItem.Document.Save();
                }
                if (neutralResxItem.Document != null && neutralResxItem.Document.Saved)
                {
                    neutralResxItem.Document.Close();
                }

                #endregion

                #region create update class xaml helper

                var fi = new FileInfo(neutralResxItem.Properties.Item("FullPath").Value.ToString());

                var ext = fi.Extension;
                var fname = fi.Name.Replace(ext, "");
                // ReSharper disable PossibleNullReferenceException
                var dirres = fi.Directory.FullName;
                // ReSharper restore PossibleNullReferenceException


                // ReSharper disable PossibleInvalidOperationException
                if (ChkHelperXml.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    var codeNeutralResx = neutralResxItem.ProjectItems.Item(1);
                    if (!codeNeutralResx.IsOpen)
                    {
                        codeNeutralResx.Open();
                    }

                    //Namespace project Default 
                    var neutralFullName = seletedProject.Properties.Item("DefaultNamespace").Value.ToString();
                    var model = (FileCodeModel2)codeNeutralResx.FileCodeModel;
                    foreach (var codeElement in model.CodeElements.Cast<CodeElement>().Where(codeElement => codeElement.Kind == vsCMElement.vsCMElementNamespace))
                    {
                        neutralFullName = codeElement.Name;
                        break;
                    }
                    // ReSharper disable PossibleNullReferenceException
                    neutralFullName += "." + new FileInfo(neutralResxItem.Name).Name.Replace(neutralResxItem.Properties.Item("Extension").Value.ToString(),"");
                    // ReSharper restore PossibleNullReferenceException
                    CreateUpdateHelperXml(seletedProject, dirres, folderItem, neutralFullName);
                }

                #endregion

                #region create resource languages

                foreach (var resfilename in (from object obj in Col0SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.IsChecked != null && chk.IsChecked.Value select chk).Select(chk => fname + "." + chk.Tag + ext))
                {
                    CreateUpdateLngResx(seletedProject, folderItem, templatePath, resfilename);
                }
                foreach (var resfilename in (from object obj in Col1SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.IsChecked != null && chk.IsChecked.Value select chk).Select(chk => fname + "." + chk.Tag.ToString() + ext))
                {
                    CreateUpdateLngResx(seletedProject, folderItem, templatePath, resfilename);
                }
                foreach (var resfilename in (from object obj in Col2SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null where chk.IsChecked != null && chk.IsChecked.Value select chk).Select(chk => fname + "." + chk.Tag.ToString() + ext))
                {
                    CreateUpdateLngResx(seletedProject, folderItem, templatePath, resfilename);
                }

                #endregion

                #region update Access modifier

                foreach (var item in (from object obj in Col0SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null && chk.Opacity.Equals(1) where chk.IsChecked != null && !chk.IsEnabled select chk).Select(chk => dirres + "\\" + fname + "." + chk.Tag + ext).Select(resfilename => Package.EnvDte.Solution.FindProjectItem(resfilename)).Where(item => item != null))
                {
                    switch (((ComboBoxItem)CboAccessMod.SelectedItem).Tag.ToString())
                    {
                        case "P":
                            {
                                item.Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
                            }
                            break;
                        case "I":
                            {
                                item.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator";
                            }
                            break;
                        case "N":
                            {
                                item.Properties.Item("CustomTool").Value = null;
                            }
                            break;
                    }
                }
                foreach (var item in (from object obj in Col1SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null && chk.Opacity.Equals(1) where chk.IsChecked != null && !chk.IsEnabled select chk).Select(chk => dirres + "\\" + fname + "." + chk.Tag + ext).Select(resfilename => Package.EnvDte.Solution.FindProjectItem(resfilename)).Where(item => item != null))
                {
                    switch (((ComboBoxItem)CboAccessMod.SelectedItem).Tag.ToString())
                    {
                        case "P":
                            {
                                item.Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
                            }
                            break;
                        case "I":
                            {
                                item.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator";
                            }
                            break;
                        case "N":
                            {
                                item.Properties.Item("CustomTool").Value = null;
                            }
                            break;
                    }
                }
                foreach (var item in (from object obj in Col2SupLng.Children select obj as CheckBox into chk where chk != null && chk.Tag != null && chk.Opacity.Equals(1) where chk.IsChecked != null && !chk.IsEnabled select chk).Select(chk => dirres + "\\" + fname + "." + chk.Tag + ext).Select(resfilename => Package.EnvDte.Solution.FindProjectItem(resfilename)).Where(item => item != null))
                {
                    switch (((ComboBoxItem)CboAccessMod.SelectedItem).Tag.ToString())
                    {
                        case "P":
                            {
                                item.Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
                            }
                            break;
                        case "I":
                            {
                                item.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator";
                            }
                            break;
                        case "N":
                            {
                                item.Properties.Item("CustomTool").Value = null;
                            }
                            break;
                    }
                }

                #endregion

                #region update project file

                UpdateProjectFile(seletedProject, folderItem, new FileInfo(neutralResxItem.Name).Name.Replace(neutralResxItem.Properties.Item("Extension").Value.ToString(), ""));

                #endregion

            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
            IsEnabled = true;
        }

        private void CreateUpdateHelperXml(Project seletedProject, string dirres, ProjectItem folderItem, string neutralFullName)
        {
            var soln = (Solution2)Package.EnvDte.Solution;
            var guidlng = seletedProject.CodeModel.Language;
            var extclass = ".vb";
            if (guidlng == CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                extclass = ".cs";
            }

            var xamlreshelper = Package.EnvDte.Solution.FindProjectItem(dirres + "\\" + UserSettings.Current.XamlClassHelper + extclass);
            if (xamlreshelper == null)
            {
                if (!File.Exists(dirres + "\\" + UserSettings.Current.XamlClassHelper + extclass))
                {
                    var templateClassPath = soln.GetProjectItemTemplate(Constants.TemplateNameClass, seletedProject.Kind);
                    if (folderItem == null)
                    {
                        seletedProject.ProjectItems.AddFromTemplate(templateClassPath, UserSettings.Current.XamlClassHelper + extclass);
                        xamlreshelper = seletedProject.ProjectItems.Item(UserSettings.Current.XamlClassHelper + extclass);
                    }
                    else
                    {
                        folderItem.ProjectItems.AddFromTemplate(templateClassPath, UserSettings.Current.XamlClassHelper + extclass);
                        xamlreshelper = folderItem.ProjectItems.Item(UserSettings.Current.XamlClassHelper + extclass);
                    }
                }
            }
            if (xamlreshelper != null)
            {
                if (!xamlreshelper.IsOpen)
                {
                    xamlreshelper.Open();
                    xamlreshelper.Document.ActiveWindow.Visible = false;
                }
                else
                {
                    xamlreshelper.Document.ActiveWindow.Visible = false;
                }

                //Namespace project Default 
                var codeNameSpace =  seletedProject.Properties.Item("DefaultNamespace").Value.ToString();
                var model = (FileCodeModel2)xamlreshelper.FileCodeModel;
                foreach (var codeElement in model.CodeElements.Cast<CodeElement>().Where(codeElement => codeElement.Kind == vsCMElement.vsCMElementNamespace))
                {
                    codeNameSpace = codeElement.Name;
                    break;
                }

                var textselect = (TextSelection)xamlreshelper.Document.Selection;
                textselect.SelectAll();
                textselect.Insert(ReadTemplateResxHelper(neutralFullName, codeNameSpace, UserSettings.Current.XamlClassHelper, extclass));
                textselect.GotoLine(1);
                xamlreshelper.Document.Save();
                xamlreshelper.Document.Close();

            }
        }

        private void UpdateProjectFile(Project seletedProject,ProjectItem folderResource, string nameNeutralResource)
        {
            var fullName = seletedProject.FullName;
            var suportedLanguages = EnvPhoneDevice.GetKeyPhoneLanguageSupport(CboPrjLng.Text) + ";";
            // ReSharper disable LoopCanBeConvertedToQuery
            var prjResFiles = seletedProject.ProjectItems;
            if (folderResource != null)
            {
                prjResFiles = folderResource.ProjectItems;
            }

            foreach (ProjectItem item in prjResFiles)
            // ReSharper restore LoopCanBeConvertedToQuery
            {
                var name = item.Name;
                if (name.StartsWith(nameNeutralResource))
                {
                    var tmp = name.Replace(nameNeutralResource + ".", "");
                    var index = tmp.IndexOf('.');
                    if (index > 0)
                    {
                        var s = tmp.Substring(0, index);
                        suportedLanguages += (s + ";");
                    }
                }
            }
            if (suportedLanguages.EndsWith(";"))
            {
                suportedLanguages = suportedLanguages.Substring(0, suportedLanguages.Length - 1);
            }
            var soln = Package.GetServiceHelper(typeof(SVsSolution)) as IVsSolution;
            if (soln != null)
            {
                IVsHierarchy selectedHierarchy;
                ErrorHandler.ThrowOnFailure(soln.GetProjectOfUniqueName(seletedProject.UniqueName, out selectedHierarchy));

                soln.SaveSolutionElement((uint) __VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, selectedHierarchy, 0);

                ErrorHandler.ThrowOnFailure(soln.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, selectedHierarchy, 0));

                var xmldoc = new XmlDocument();
                xmldoc.Load(fullName);
                // ReSharper disable PossibleNullReferenceException
                var ns = xmldoc.GetElementsByTagName("Project")[0].Attributes["xmlns"].Value;
                // ReSharper restore PossibleNullReferenceException
                var nodes = xmldoc.GetElementsByTagName("SupportedCultures");
                if (nodes.Count == 1)
                {
                    nodes[0].InnerText = suportedLanguages;
                }
                else
                {
                    nodes = xmldoc.GetElementsByTagName("AssemblyName");
                    if (nodes.Count == 1 && nodes[0].ParentNode != null)
                    {
                        var elem = xmldoc.CreateElement("SupportedCultures", ns);
                        elem.InnerText = suportedLanguages;
                        nodes[0].ParentNode.AppendChild(elem);
                    }
                }
                xmldoc.Save(fullName);
                Package.EnvDte.ExecuteCommand("Project.ReloadProject");
            }
        }

        private static string ReadTemplateResxHelper(string fullNameNeutralResxClass, string nameSpace, string className, string extclass)
        {
            var result = string.Empty;
            var fullNameClassResxNeutral = string.Empty;
            if (extclass == ".cs")
            {
                fullNameClassResxNeutral = Constants.TemplateResNameHelperCs;
            }
            else if (extclass == ".vb")
            {
                fullNameClassResxNeutral = Constants.TemplateResNameHelperVb;
            }
            using (
                var resourceStream =
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(fullNameClassResxNeutral))
            {
                //Verify if the resource is valid
                if (resourceStream != null)
                {
                    //Prepare the stream to read
                    using (var resourceReader = new StreamReader(resourceStream))
                    {
                        // Read the stream and get the html
                        result = resourceReader.ReadToEnd();
                    }
                    result = result.Replace("{0}", nameSpace);
                    result = result.Replace("{1}", className);
                    result = result.Replace("{2}", fullNameNeutralResxClass);
                }
            }
            return result;
        }

        private void CboFilesResxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var value = string.Empty;
            if (e.AddedItems.Count != 0)
            {
                value = (string)e.AddedItems[0];
            }
            var fi = new FileInfo(_rootproject + value);
            // ReSharper disable PossibleNullReferenceException
            if (_rootproject == fi.Directory.FullName + "\\")
            {
                CboTargetFolder.SelectedIndex = 0;
            }
            else
            {
                CboTargetFolder.SelectedItem = fi.Directory.FullName.Replace(_rootproject, "");
            }
            // ReSharper restore PossibleNullReferenceException
        }

        private void CreateUpdateLngResx(Project seletedProject, ProjectItem folderItem, string templatePath, string resfilename)
        {
            ProjectItem lngResxItem;
            if (folderItem == null)
            {
                seletedProject.ProjectItems.AddFromTemplate(templatePath, resfilename);
                lngResxItem = seletedProject.ProjectItems.Item(resfilename);
            }
            else
            {
                folderItem.ProjectItems.AddFromTemplate(templatePath, resfilename);
                lngResxItem = folderItem.ProjectItems.Item(resfilename);
            }
            lngResxItem.Document.ActiveWindow.Visible = false;
            switch (((ComboBoxItem)CboAccessMod.SelectedItem).Tag.ToString())
            {
                case "P":
                    {
                        lngResxItem.Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
                    }
                    break;
                case "I":
                    {
                        lngResxItem.Properties.Item("CustomTool").Value = "ResXFileCodeGenerator";
                    }
                    break;
                case "N":
                    {
                        lngResxItem.Properties.Item("CustomTool").Value = null;
                    }
                    break;
            }
            if (lngResxItem.Document != null && !lngResxItem.Document.Saved)
            {
                lngResxItem.Document.Save();
            }
            if (lngResxItem.Document != null && lngResxItem.Document.Saved)
            {
                lngResxItem.Document.Close();
            }
        }

        private void CboTargetFolderSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                MarkPatternResources((string)CboFilesResx.SelectedItem, (string)e.AddedItems[0]);
            }
        }
    }
}



